#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRandomGenerator>
#include <QMessageBox>

const int TOTAL_CELLS = 81;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_playerCount(2),
    m_currentPlayer(0),
    m_positions(3, 0),
    m_gameOver(false)
{
    ui->setupUi(this);
    setWindowTitle("蛇形探险棋 - 2-3人对战版");

    // 初始化玩家选择下拉框
    ui->playerComboBox->addItems({"2人游戏", "3人游戏"});

    // 初始隐藏3P棋子
    ui->gameBoard->setPlayerVisible(2, false);
    updateUI();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_rollButton_clicked()
{
    if(m_gameOver) return;

    // 生成骰子点数
    int diceValue = QRandomGenerator::global()->bounded(1, 7);
    m_positions[m_currentPlayer] += diceValue;

    // 处理到达终点
    if(m_positions[m_currentPlayer] >= TOTAL_CELLS-1) {
        m_positions[m_currentPlayer] = TOTAL_CELLS-1;
        checkWinner();
    }

    // 移动棋子并更新界面
    ui->gameBoard->movePlayer(m_currentPlayer, m_positions[m_currentPlayer]);
    m_currentPlayer = (m_currentPlayer + 1) % m_playerCount;
    updateUI();
}

void MainWindow::on_resetButton_clicked()
{
    // 重置游戏状态
    m_positions.fill(0);
    m_currentPlayer = 0;
    m_gameOver = false;
    ui->gameBoard->reset();
    updateUI();
    setGameActive(true);
}

void MainWindow::on_playerComboBox_currentIndexChanged(int index)
{
    // 更新玩家数量并重置游戏
    m_playerCount = index + 2;
    ui->gameBoard->setPlayerVisible(2, m_playerCount == 3);
    on_resetButton_clicked();
}

void MainWindow::updateUI()
{
    QStringList status;
    for(int i = 0; i < m_playerCount; ++i) {
        status << QString("玩家%1: %2").arg(i+1).arg(m_positions[i]);
    }

    // 更新状态标签
    ui->statusLabel->setText(QString("当前玩家：玩家%1  骰子点数：%2")
                                 .arg(m_currentPlayer + 1)
                                 .arg(m_positions[m_currentPlayer]));
    ui->positionsLabel->setText(status.join(" | "));
}

void MainWindow::checkWinner()
{
    m_gameOver = true;
    QMessageBox::information(this, "游戏结束",
                             QString("玩家%1 获得胜利！").arg(m_currentPlayer + 1));
    setGameActive(false);
}

void MainWindow::setGameActive(bool active)
{
    ui->rollButton->setEnabled(active);
    QString style = active ? "background: #4CAF50;" : "background: #9E9E9E;";
    ui->rollButton->setStyleSheet(style);
}
